import { defineStore } from 'pinia';
import { UserState } from './types';

import { localStorageWrap } from '@/utils/storage';
import { loginApi, logoutApi } from '@/api/logreg';
import { LoginForm } from '@/api/logreg/types';
import { getUserInfo } from '@/api/user';

const useUserStore = defineStore({
  id: 'user',
  state: (): UserState => ({
    token: localStorageWrap.get('token') || '',
    yhm: '',
    sjh: '',
    avatar: ''
  }),
  actions: {
    async RESET_STATE() {
      this.$reset();
    },
    /**
     * 登录
     */
    login(data: LoginForm) {
      const { sjh, mm } = data;
      return new Promise((resolve, reject) => {
        loginApi({
          sjh: sjh.trim(),
          mm: mm
        })
          .then((res: any) => {
            const accessToken = res.data.token;
            localStorageWrap.set('token', accessToken);
            this.token = accessToken;
            this.yhm = res.data.name;
            this.sjh = sjh.trim();
            resolve(accessToken);
          })
          .catch(error => {
            reject(error);
          });
      });
    },

    /**
     *  获取用户信息
     */
    // getUserInfo() {
    //   return new Promise((resolve, reject) => {
    //     getUserInfo()
    //       .then(res => {
    //         const { avatar } = res.data;
    //         this.avatar = avatar;
    //         resolve(res.data);
    //       })
    //       .catch(error => {
    //         reject(error);
    //       });
    //   });
    // },

    /**
     *  注销
     */
    logout() {
      return new Promise((resolve, reject) => {
        logoutApi()
          .then(() => {
            localStorageWrap.remove('token');
            this.RESET_STATE();
            resolve(null);
          })
          .catch(error => {
            reject(error);
          });
      });
    },

    /**
     * 清除 Token
     */
    resetToken() {
      return new Promise(resolve => {
        localStorageWrap.remove('token');
        this.RESET_STATE();
        resolve(null);
      });
    }
  }
});

export default useUserStore;
